package com.biz.hunter.dao;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.biz.hunter.db.entity.JobDesc;
import com.biz.hunter.db.entity.JobTitle;
import com.biz.hunter.dbutil.BaseDAO;

@Repository
public class JobTitleDAO {
	private static final String SQL_GET_ID = "select * from tb_jobtitle  where id = ?";
	private static final String SQL_GET_NAME = "select * from tb_jobtitle  where name = ?";
	private static final String SQL_GET_NAME_ID = "SELECT * FROM tb_jobtitle  WHERE name = ? AND id <>?";
	
	private static final String SQL_GET_ALL = "select * from tb_jobtitle";
	private static final String SQL_GET_ALL_WITH_LIMIT = "select * from tb_jobtitle where 1=1 ";
	private static final String SQL_GET_ALL_COUNT = "SELECT COUNT(*) FROM tb_jobtitle where 1=1 ";
	
	private static final String SQL_SAVE = "INSERT INTO tb_jobtitle(name, postype) VALUES(?, ?)";
	private static final String SQL_UPDATE = "UPDATE tb_jobtitle SET name=?, postype=? WHERE id=?";
	private static final String SQL_DELETE ="DELETE FROM tb_jobtitle WHERE id=?";

	public Long getCountOfAll(String name, Integer postype) {
		String sql = SQL_GET_ALL_COUNT;
		if (StringUtils.hasText(name)) {
			sql += " and name like '" + name + "'";
		}
		if (postype != null) {
			sql += " and postype =" + postype + " ";
		}
		return (Long) BaseDAO.queryOneRowOneCol(sql);
	}

	public List<JobTitle> getAllWithLimit(String name, Integer postype, 
			long start, long length) {
		String sql = SQL_GET_ALL_WITH_LIMIT;
		if (StringUtils.hasText(name)) {
			sql += " and name like '" + name + "'";
		}
		if (postype != null) {
			sql += " and postype =" + postype + " ";
		}
		
		sql += " LIMIT ?, ?";
		return BaseDAO.queryForList(JobTitle.class, sql, start, length);
	}

	public List<JobTitle> getALL() {
		return BaseDAO.queryForList(JobTitle.class, SQL_GET_ALL);
	}

	public JobTitle getById(long Id) {
		return BaseDAO.queryForObject(JobTitle.class, SQL_GET_ID, Id);
	}

	public JobTitle getByName(String name) {
		return BaseDAO.queryForObject(JobTitle.class, SQL_GET_NAME, name);
	}

	public JobTitle getByNameAndNotId(String name, long id) {
		return BaseDAO.queryForObject(JobTitle.class, SQL_GET_NAME_ID, name, id);
	}

	public int delete(long jobid) {
		if (jobid <=0) {
			return -1;
		}
		return BaseDAO.execute(SQL_DELETE, jobid);
	}
	
	public int update(JobTitle jd) {
		return BaseDAO.execute(SQL_UPDATE, jd.getName(), jd.getPostype(), jd.getId());
	}
	
	public long save(JobTitle jd) {
		if (jd == null) {
			return -1;
		}

		Long result = BaseDAO.save(SQL_SAVE, jd.getName(), jd.getPostype());
		if (result != null) {
			return result.longValue();
		}
		return -1;
	}

}
